import {message, Modal, Radio, Tooltip, Divider, Button, Select, Input, Col, Space} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import ProTable from '@ant-design/pro-table';
import {ActionType, ProColumns} from '@ant-design/pro-table/lib/Table';
import {SorterResult} from 'antd/es/table/interface';
import {connect, Dispatch} from 'umi';
import './style.less';
import {editUserPri, getUserPri} from '@/services/information';

import {
  DatabaseOutlined,
  EditOutlined,
} from '@ant-design/icons';

import {Identity, IResponse, UserTableListItem} from '../type';
import {ConnectState} from '@/models/connect';
import * as dayjs from 'dayjs';
import {debounce, getSubStr, sortDate, sortString} from '@/utils/common';

const RightsManagement = React.lazy(() => import('../components/RightsManagement'));
const AddUser = React.lazy(() => import('./components/AddUser'));
const EditProject = React.lazy(() => import('./components/EditProject'));

interface UserProps {
  dispatch: Dispatch;
  users: Array<UserTableListItem>;
  identitys: Array<Identity>;
  loading?: boolean
}

const UserList: React.FC<UserProps> = (props) => {
  const [identityModalVisible, handleIdentityModalVisible] = useState<boolean>(false); // 分配身份弹框
  const [addUserVisible, setAddUserVisible] = useState<boolean>(false); // 添加用户
  const [editProjectVisible, setEditProjectVisible] = useState<boolean>(false); // 项目编辑
  const [identityId, setIdentityId] = useState<number>(6); // 分配身份类型ID
  const [currentJurisdiction, setCurrentJurisdiction] = useState<any>({})
  const [distributionObj, setDistributionObj] = useState<UserTableListItem>({
    active: false,
    department: '',
    id: 0,
    name: '',
    username: '',
  }); // 操作的用户对象

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false); // 权限管理弹框
  const [showBtn] = useState<boolean>(true); // 权限管理弹框

  const [current, setCurrent] = useState<any>({});//当前行
  const [projects, setProjects] = useState([]);//当前行
  const [queryParams, setQueryParams] = useState<{}>({});
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();
  const {users, identitys, dispatch, loading} = props;

  function getProjects() {
    getUserPri().then(resp => {
      const {payload} = resp;
      if (payload && payload.length > 0) {
        let arr = payload.map((item: any) => ({value: item.projectName, label: item.projectName}));
        setProjects(arr);
      }
    });
  }

  // 获取表格列表
  useEffect(() => {
    if (users.length === 0) {
      dispatch({
        type: 'userManage/fetchUsers',
      });
    }
    getProjects();
  }, []);


  // 显示权限管理弹框
  const authorityManagement = (item: UserTableListItem) => {
    setCurrent(item);
    editUserPri(item.id).then(resp => {
      setCurrentJurisdiction(resp.payload)
      setEditProjectVisible(true);
    })
  };

  function handleDataPri(item: UserTableListItem) {
    setDistributionObj(item);
    handleUpdateModalVisible(true);
  }

  // 表格单元格定义
  const columns: ProColumns<UserTableListItem>[] = [
    {
      title: '用户名',
      dataIndex: 'name',
      hideInSearch: true,
      sorter: (a, b) => sortString(a, b, 'name'),
      rules: [
        {
          required: true,
          message: '规则名称为必填项',
        },
      ],
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '通行证账号',
      dataIndex: 'username',
      valueType: 'textarea',
      hideInSearch: true,
      className: 'test',
      sorter: (a, b) => sortString(a, b, 'username'),
    },
    {
      title: '部门',
      dataIndex: 'department',
      hideInSearch: true,
      renderText: (text: string) => getSubStr(text, 5, 12, 10),
      ellipsis: true,
      sorter: (a, b) => sortString(a, b, 'department'),
    },
    {
      title: '项目',
      dataIndex: 'projects',
      hideInSearch: true,
      sorter: (a, b) => sortString(a, b, 'projects'),
      renderText: (text: string) => getSubStr(text, 1, 5, 3),
      ellipsis: true,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      hideInSearch: true,
      sorter: (a, b) => sortString(a, b, 'createBy'),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      sorter: (a, b) => sortDate(a, b, 'createTime'),
      renderText: (text) => {
        return dayjs(text, 'yyyy-MM-dd HH:mm:ss').format('YYYY-MM-DD');
      },

    },
    // {
    //   title: '状态',
    //   dataIndex: 'active',
    //   // hideInForm: true,
    //   hideInSearch: true,
    //   valueEnum: {
    //     true: {
    //       text: '正常',
    //       status: 'Success',
    //     },
    //     false: {
    //       text: '已禁用',
    //       status: 'Error',通行证账号
    //     },
    //   },
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: UserTableListItem) => (
        <>
          <Space>
            <Tooltip title={'项目编辑'}>
              <EditOutlined onClick={() => authorityManagement(record)}/>
            </Tooltip>
            {showBtn ?
              <Tooltip title={'数据权限'}>
                <DatabaseOutlined onClick={() => handleDataPri(record)}/>
              </Tooltip>
              : null
            }
          </Space>
        </>
      ),
    },
  ];

  // 分配身份样式
  const radioStyle = {
    display: 'block',
    height: '30px',
    lineHeight: '30px',
  };

  // 显示分配身份弹框
  const distribution = (item: UserTableListItem) => {
    if (identitys.length === 0) {
      dispatch({
        type: 'userManage/fetchIdentityList',
      });
    }
    handleIdentityModalVisible(true);
    setDistributionObj(item);
  };

  // 保存分配身份
  const identityUpdate = () => {
    dispatch({
      type: 'userManage/submitIdentity',
      payload: {identityId, userId: distributionObj.id},
      callback: (response: IResponse) => {
        const {header} = response;
        if (header.code === 200) {
          message.success('分配成功');
        } else {
          message.warning('分配失败');
        }
      },
    });
    handleIdentityModalVisible(false);
  };


  // 获得表格滚动区域高度
  let tabelScroll = 300;
  const wrapperRef = useRef<any>();
  if (wrapperRef && wrapperRef.current) {
    tabelScroll = wrapperRef.current.scrollHeight - 280;
  }

  const dataSource = users.filter((value: UserTableListItem) => {
    if (value.username === 'admin') {
      return false;
    }
    const keys = Object.keys(queryParams);
    if (keys.length === 0) {
      return true;
    }
    for (const i in keys) {
      const key = keys[i];
      if (value[key].toString().indexOf(queryParams[key]) === -1) {
        return false;
      }
    }
    return true;
  }).sort(
    (a, b) => sortDate(b, a, 'createTime')
  );

  const handleInputChange = (e: any) => {
    const {value} = e.target;
    setQueryParams({name: value});

  };
  const handleSelectChange = (v: string) => {
    if (v) {
      setQueryParams({projects: v});
    } else {
      setQueryParams({projects: ''});
    }
  };


  return (
    <div style={{height: '100%'}} ref={wrapperRef}>

      <div className={'table-toolbar'}>
        <Col span={6}>
          <Input allowClear
                 placeholder={'搜索用户名'}
                 onChange={debounce(handleInputChange, 800)}
          ></Input>
        </Col>
        <Col span={6} className={'gutter-16'}>
          <Select style={{width: '100%'}}
                  placeholder={'全部项目'}
                  allowClear
                  onChange={handleSelectChange}
                  options={projects}
          >
          </Select>
        </Col>
        <Col span={11} className={'toolbar'}>
          <Button key="button" onClick={() => setAddUserVisible(true)}>
            添加用户
          </Button>
        </Col>

      </div>
      <ProTable<UserTableListItem>
        search={false}
        scroll={{y: tabelScroll}}
        loading={loading}
        actionRef={actionRef}
        rowKey="id"
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<UserTableListItem>;

          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        dataSource={dataSource}
        onSubmit={(params) => {
          setQueryParams(params);
        }}
        columns={columns}

      />
      {updateModalVisible ? (
        <React.Suspense fallback={null}>
          <RightsManagement
            userId={distributionObj.id}
            parentType="User"
            onCancel={() => {
              handleUpdateModalVisible(false);
            }}
            visible={updateModalVisible}
          />
        </React.Suspense>
      ) : null}
      {editProjectVisible && currentJurisdiction ? (
        <React.Suspense fallback={null}>
          <EditProject
            title={'项目权限'}
            row={current}
            data={currentJurisdiction}
            onCancel={() => {
              setEditProjectVisible(false);
            }}
            visible={editProjectVisible}
          />
        </React.Suspense>
      ) : null}
      {addUserVisible ? (
        <React.Suspense fallback={null}>
          <AddUser
            onCancel={() => {
              setAddUserVisible(false);
            }}
            visible={addUserVisible}
          />
        </React.Suspense>
      ) : null}

      <Modal
        title="身份分配"
        visible={identityModalVisible}
        onOk={identityUpdate}
        onCancel={() => handleIdentityModalVisible(false)}
      >
        <Radio.Group
          value={identityId}
          onChange={(e) => {
            setIdentityId(e.target.value);
          }}
        >
          {identitys.map((v, idx) => {
            return (
              <Radio key={idx} style={radioStyle} value={v.id}>
                {v.name}
              </Radio>
            );
          })}
        </Radio.Group>
      </Modal>

    </div>
  );
};
export default connect(({userManage, loading}: ConnectState) => ({
  users: userManage.users || [],
  identitys: userManage.identitys || [],
  loading: loading.effects['userManage/fetchUsers'],
}))(UserList);
